define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 动态引入通用脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/index.js';
            document.head.appendChild(script);
            
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: '/communityapply/communityapply/index',
                    add_url: '/communityapply/communityapply/add',
                    edit_url: '/communityapply/communityapply/edit',
                    multi_url: '/communityapply/communityapply/multi',
                    del_url: '/communityapply/communityapply/del',
                    dragsort_url: '/ajax/weigh',
                    table: 'eb_apply_form',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                escape: false,
                pk: 'id',
                sortName: 'weigh',
                sortOrder: 'desc',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: __('Id'), sortable: true },
                        { field: 'title', title: '项目名称', sortable: true, align:'left' },
                        { field: 'start_time', title: '开始时间', formatter: Table.api.formatter.datetime, sortable: true },
                        { field: 'end_time', title: '结束时间', formatter: Table.api.formatter.datetime, sortable: true },
                        { field: 'quota', title: '名额', sortable: true },
                        { field: 'city_id_text', title: '城市', sortable: true },
                        { field: 'school_id_text', title: '学校', sortable: true },
                        { field: 'create_time', title: '创建时间', formatter: Table.api.formatter.datetime, sortable: true },
                        { field: 'status', title: '状态', formatter: Controller.api.formatter.status, events: Controller.api.events.status },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'edit',
                                    title: __('Edit'),
                                    icon: 'fa fa-pencil',
                                    classname: 'btn btn-xs btn-success btn-editone btn-dialog',
                                    url: 'communityapply/communityapply/edit',
                                    extend: 'data-area=["80%","80%"] data-title="编辑社区课程报名"'
                                },
                                {
                                    name: 'del',
                                    title: __('Delete'),
                                    icon: 'fa fa-trash',
                                    classname: 'btn btn-xs btn-danger btn-delone',
                                    url: 'communityapply/communityapply/del'
                                }
                            ]
                        }
                    ]
                ]
            });
            
            // 绑定筛选按钮事件
            $('#btn-filter').on('click', function() {
                var cityId = $('#c-cityarea_id').val();
                var schoolId = $('#c-school_id').val();
                
                var queryParams = table.bootstrapTable('getOptions').queryParams;
                table.bootstrapTable('refresh', {
                    query: {
                        city_id: cityId,
                        school_id: schoolId
                    }
                });
            });
            
            // 绑定重置按钮事件
            $('#btn-reset-filter').on('click', function() {
                $('#c-cityarea_id').val('').trigger('change');
                $('#c-school_id').val('').trigger('change');
                table.bootstrapTable('refresh', {
                    query: {}
                });
            });

            // 绑定删除成功后刷新事件
            $(document).on('fa.event.refreshTable', function(e, table) {
                if (table && table.length) {
                    table.bootstrapTable('refresh');
                }
            });

            // 重写删除按钮事件，确保删除后刷新
            $(document).on('click', '.btn-delone', function() {
                var that = this;
                var url = $(this).data('url') || $(this).attr('href');
                var id = $(this).data('id') || $(this).closest('tr').find('input[type="checkbox"]').val();
                
                Layer.confirm('确定要删除这条记录吗？', function(index) {
                    Backend.api.ajax({
                        url: url,
                        data: {ids: id}
                    }, function(data) {
                        Layer.msg('删除成功');
                        table.bootstrapTable('refresh'); // 强制刷新表格
                    });
                    Layer.close(index);
                });
                return false;
            });

            Table.api.bindevent(table);
            Controller.api.bindevent();
        },
        add: function () {
            // 动态引入通用脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            
            // 监听是否指定班级开关变化
            $(document).on("change", "#c-is_classes", function () {
                var value = $(this).val();
                if (value == '1') {
                    $('#class-items-group').show();
                    Controller.api.loadClassItems();
                } else {
                    $('#class-items-group').hide();
                }
            });

            Controller.api.bindevent();
        },
        edit: function () {
            // 动态引入通用脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js';
            document.head.appendChild(script);
            
            // 监听是否指定班级开关变化
            $(document).on("change", "#c-is_classes", function () {
                var value = $(this).val();
                if (value == '1') {
                    $('#class-items-group').show();
                    Controller.api.loadClassItems();
                } else {
                    $('#class-items-group').hide();
                }
            });

            // 页面加载时检查是否需要显示班级选择
            if ($('#c-is_classes').val() == '1') {
                Controller.api.loadClassItems();
            }

            // 初始化选项卡切换
            Controller.api.initTabs();
            
            // 初始化预约详情表格
            Controller.api.initBookingTable();
            
            // 绑定刷新按钮事件
            $('#refresh-booking-list').on('click', function() {
                Controller.api.loadBookingDetails();
            });

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            
            // 加载班级列表
            loadClassItems: function() {
                $.ajax({
                    url: '/ocation/ocation/getClassList',
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        var $select = $('#c-class_items');
                        $select.empty();
                        
                        if (data && data.length > 0) {
                            $.each(data, function(index, item) {
                                var selected = '';
                                // 编辑时检查是否已选中
                                if (typeof row !== 'undefined' && row.class_items) {
                                    var classItems = JSON.parse(row.class_items);
                                    if (classItems.indexOf(item.id.toString()) !== -1) {
                                        selected = 'selected';
                                    }
                                }
                                $select.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
                            });
                        }
                        
                        // 刷新选择器
                        $select.trigger('change');
                    },
                    error: function(xhr, status, error) {
                        // 获取班级列表失败处理
                    }
                });
            },
            
            // 初始化选项卡切换
            initTabs: function() {
                // 绑定手动点击事件（备用方案）
                $('.nav-tabs a').on('click', function(e) {
                    e.preventDefault();
                    var target = $(this).attr('href');
                    
                    // 手动切换tab
                    $('.nav-tabs li').removeClass('active');
                    $(this).parent().addClass('active');
                    
                    $('.tab-pane').removeClass('active in').addClass('fade');
                    $(target).removeClass('fade').addClass('active in');
                    
                    // 如果是预约详情tab，初始化表格
                    if (target === '#booking-details') {
                        setTimeout(function() {
                            var $table = $('#booking-details-table');
                            if (!$table.hasClass('bootstrap-table')) {
                                Controller.api.initBookingTable();
                            } else {
                                Controller.api.loadBookingDetails();
                            }
                        }, 300);
                    }
                });
                
                // 绑定选项卡切换事件
                $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                    var target = $(e.target).attr("href");
                    
                    // 使用Bootstrap标准方法切换tab
                    $('.tab-pane').removeClass('active in').addClass('fade');
                    $(target).removeClass('fade').addClass('active in');
                    
                    // 如果切换到预约详情选项卡，初始化并加载数据
                    if (target === '#booking-details') {
                        // 延迟执行，确保DOM已经更新
                        setTimeout(function() {
                            var $table = $('#booking-details-table');
                            
                            // 如果表格还没有初始化，先初始化
                            if (!$table.hasClass('bootstrap-table')) {
                                Controller.api.initBookingTable();
                            } else {
                                // 如果已经初始化，直接刷新数据
                                Controller.api.loadBookingDetails();
                            }
                        }, 200);
                    }
                });
            },
            
            // 初始化预约详情表格
            initBookingTable: function() {
                var $table = $('#booking-details-table');
                if ($table.length > 0 && !$table.hasClass('bootstrap-table')) {
                    
                    $table.bootstrapTable({
                        url: '/communityapply/communityapply/getBookingDetails',
                        method: 'get',
                        queryParams: function(params) {
                            var formId = $('input[name="row[id]"]').val();
                            
                            return {
                                form_id: formId,
                                offset: params.offset,
                                limit: params.limit,
                                search: params.search,
                                sort: params.sort,
                                order: params.order
                            };
                        },
                        responseHandler: function(res) {
                            // 处理控制器直接返回的格式 {total: 114, rows: [...]}
                            if (res.total !== undefined && res.rows !== undefined) {
                                return {
                                    total: res.total,
                                    rows: res.rows
                                };
                            } 
                            // 处理FastAdmin标准返回格式 {code: 1, data: [...], count: 114}
                            else if (res.code == 1) {
                                return {
                                    total: res.count || 0,
                                    rows: res.data || []
                                };
                            } 
                            // 处理错误情况
                            else {
                                return {
                                    total: 0,
                                    rows: []
                                };
                            }
                        },
                        sidePagination: 'server',
                        pagination: true,
                        pageSize: 10,
                        pageList: [10, 25, 50, 100],
                        search: true,
                        showRefresh: true,
                        showToggle: false,
                        showColumns: false,
                        sortName: 'create_time',
                        sortOrder: 'desc',
                        escape: false,
                        columns: [
                            {field: 'id', title: 'ID', width: 60, sortable: true},
                            {field: 'user_name', title: '姓名', width: 100, sortable: true},
                            {field: 'user_gender', title: '性别', width: 80},
                            {field: 'user_mobile', title: '电话', width: 120},
                            {field: 'class_name', title: '班级', width: 150},
                            {field: 'create_time', title: '报名时间', width: 160, sortable: true, formatter: function(value) {
                                return value ? new Date(value * 1000).toLocaleString() : '';
                            }},
                            {field: 'status', title: '状态', width: 80, formatter: function(value) {
                                var statusMap = {0: '待审核', 1: '已通过', 2: '已拒绝'};
                                var colorMap = {0: 'warning', 1: 'success', 2: 'danger'};
                                return '<span class="label label-' + (colorMap[value] || 'default') + '">' + 
                                       (statusMap[value] || '未知') + '</span>';
                            }},
                            {field: 'operate', title: '操作', width: 120, formatter: function(value, row) {
                                var html = '';
                                if (row.status == 0) {
                                    html += '<a href="javascript:;" class="btn btn-xs btn-success btn-approve" data-id="' + row.id + '">通过</a> ';
                                    html += '<a href="javascript:;" class="btn btn-xs btn-danger btn-reject" data-id="' + row.id + '">拒绝</a>';
                                }
                                return html;
                            }}
                        ],
                        onLoadError: function(status) {
                            // 表格加载错误处理
                        },
                        onLoadSuccess: function(data) {
                            // 表格加载成功处理
                        },
                        onRefresh: function() {
                            // 表格刷新事件
                        },
                        onPreBody: function() {
                            // 表格准备渲染
                        }
                    });
                    
                    // 绑定操作按钮事件
                    $table.on('click', '.btn-approve', function() {
                        var id = $(this).data('id');
                        Controller.api.updateBookingStatus(id, 1);
                    });
                    
                    $table.on('click', '.btn-reject', function() {
                        var id = $(this).data('id');
                        Controller.api.updateBookingStatus(id, 2);
                    });
                } else if ($table.hasClass('bootstrap-table')) {
                    Controller.api.loadBookingDetails();
                }
            },
            
            // 加载预约详情数据
            loadBookingDetails: function() {
                var $table = $('#booking-details-table');
                if ($table.length > 0) {
                    $table.bootstrapTable('refresh');
                }
            },
            
            // 更新预约状态
            updateBookingStatus: function(id, status) {
                var statusText = status == 1 ? '通过' : '拒绝';
                Layer.confirm('确定要' + statusText + '这个申请吗？', function(index) {
                    $.ajax({
                        url: '/communityapply/communityapply/updateBookingStatus',
                        type: 'POST',
                        data: {id: id, status: status},
                        dataType: 'json',
                        success: function(data) {
                            if (data.code == 1) {
                                Layer.msg(statusText + '成功');
                                $('#booking-details-table').bootstrapTable('refresh');
                            } else {
                                Layer.msg(data.msg || statusText + '失败');
                            }
                        },
                        error: function() {
                            Layer.msg('操作失败，请重试');
                        }
                    });
                    Layer.close(index);
                });
            },
            
            formatter: {
                status: function (value, row, index) {
                    var colorArr = {
                        '0': 'danger',
                        '1': 'success'
                    };
                    var textArr = {
                        '0': '禁用',
                        '1': '正常'
                    };
                    var color = typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                    var text = typeof textArr[value] !== 'undefined' ? textArr[value] : value;
                    return '<span class="label label-' + color + '">' + text + '</span>';
                }
            },
            
            events: {
                status: {
                    'click .btn-change-status': function (e, value, row, index) {
                        e.preventDefault();
                        e.stopPropagation();
                        var that = this;
                        var status = row.status == '1' ? '0' : '1';
                        Backend.api.ajax({
                            url: 'communityapply/communityapply/multi',
                            data: {
                                ids: row.id,
                                params: 'status=' + status
                            }
                        }, function (data) {
                            $(that).closest("table").bootstrapTable('refresh');
                        });
                    }
                }
            }
        }
    };
    return Controller;
});